package com.wish.g01.business.es;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.wish.g01.base.entity.TbHouseInfo;
import com.wish.g01.base.service.ITbHouseInfoService;
import com.wish.g01.business.util.ThredQuery;
import com.wish.g01.business.vo.HouseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @Classname InitFactory
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/6/13 8:29
 * @Created by wupenghao
 */
@Component
@Slf4j
public class InitFactory implements InitializingBean {

    @Autowired
    HouseEeRepostory houseEeRepostory;

    @Autowired
    ITbHouseInfoService tbHouseInfoService;

    @Autowired
    ThreadPoolTaskExecutor poolTaskExecutor;

    @Override
    public void afterPropertiesSet() throws Exception {
      /*  QueryWrapper<HouseInfo> houseWrapper = new QueryWrapper<>();
        // 查询房源列表
        List<TbHouseInfo> list1 = tbHouseInfoService.list();
        List<HouseInfo> list = BeanUtil.copyToList(list1, HouseInfo.class);
        // 添加到es
        houseEeRepostory.saveAll(list);*/
            long start = System.currentTimeMillis();
            //返回结果
            List<TbHouseInfo> result = new ArrayList<>();
            // 通过count查到数据总量
            int count = tbHouseInfoService.count();

            int num = 2000;//每次查询的条数
            //需要查询的次数
            int times = count / num;
            if (count % num != 0) {
                times = times + 1;
            }
            //开始查询的行数
            int bindex = 0;
            //定义最大长度的线程池  防止线程过多
            poolTaskExecutor.setMaxPoolSize(15);
            //添加任务
            for (int i = 0; i < times; i++) {
                // 构建线程
                Callable<List<TbHouseInfo>> qfe = new ThredQuery(tbHouseInfoService, bindex, num);
                // 提交线程得到返回值
                Future<List<TbHouseInfo>> future = poolTaskExecutor.submit(qfe);
                List<TbHouseInfo> infoList = future.get();
                // 添加到集合
                if (CollectionUtils.isNotEmpty(infoList)) {
                    result.addAll(infoList);
                }
                bindex = bindex + num;
            }
            // 关闭线程池
            long end = System.currentTimeMillis();
            if (log.isInfoEnabled()) {
                log.info("开启多线程查询导出数据耗时:{},共:{}条", (end - start), result.size());
            }
            //保存es
            List<HouseInfo> list = BeanUtil.copyToList(result, HouseInfo.class);
            // 添加到es
            houseEeRepostory.saveAll(list);
    }


}
